package com.wind.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author Wind
 */
@Component
public class RequestUrlInterceptor implements HandlerInterceptor {

    @Value("${ipList}")
    private String ipList;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        String url = request.getRequestURL().toString();
        if (StrUtil.isNotEmpty(ipList)){
            String[] ipArr = ipList.split(",");
            List<String> ipLists = CollUtil.newArrayList(ipArr);
            String nowIp = IpUtils.getRealIP(request);
            if (StrUtil.isNotEmpty(nowIp)){
                if (!ipLists.contains(nowIp)){
                    response.getWriter().append("<h1 style=\"text-align:center;\">IP is not in the whitelist, please contact the administrator!</h1>");
                    return false;
                }
            }
        }
        return true;
    }
}
